<template>
  <div class="app-container">
    <el-form
        :model="queryParams"
        ref="queryRef"
        v-show="showSearch"
        label-width="80px"
    >
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="用户名称" prop="customerName">
            <el-input
              v-model="queryParams.customerName"
              placeholder="请输入用户名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="用户电话" prop="customerPhone">
            <el-input
              v-model="queryParams.customerPhone"
              placeholder="请输入用户电话"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分配类型" prop="customerAuto">
            <el-select
              v-model="queryParams.customerAuto"
              placeholder="请选择分配类型"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_fp"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="服务人员" prop="receiverBy">-->
<!--            <el-input-->
<!--              v-model="queryParams.receiverBy"-->
<!--              placeholder="请输入服务人员"-->
<!--              clearable-->
<!--              @keyup.enter="handleQuery"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="8">
          <el-form-item label="工单状态" prop="customerFlag">
            <el-select
              v-model="queryParams.customerFlag"
              placeholder="请选择状态"
              clearable
            >
              <el-option
                v-for="dict in dict.type.sys_flag"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['web:CustomerRepair:add']"
        >新增
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            size="mini"-->
<!--            icon="el-icon-edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['web:CustomerRepair:edit']"-->
<!--        >修改-->
<!--        </el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            size="mini"
            type="danger"
            plain
            icon="el-icon-delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['web:CustomerRepair:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
        v-loading="loading"
        :data="CustomerRepairList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column
          label="用户ID"
          align="center"
          prop="customerId"
          v-if="false"
      />

<!--      展示表格-->
      <el-table-column width="180" label="工单编号" align="center" prop="customerKey" />
      <el-table-column width="120" label="服务类别" align="center" prop="customerHelp" />
      <el-table-column label="工单状态" align="center" prop="customerFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_flag" :value="scope.row.customerFlag"/>
        </template>
      </el-table-column>
      <el-table-column width="120" label="接单时长" align="center" prop="customerTimer">
        <template slot-scope="scope">
          <span :style="{color: (scope.row.customerFlag == 0 || scope.row.customerFlag == 99) && getTimeOut(scope.row) == '超时' ? 'red' : ''}">{{ getTimeOut(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" label="客户姓名" align="center" prop="liaison" />
      <el-table-column width="110" label="客户电话" align="center" prop="liaisonPhone" />
      <el-table-column width="100" label="发起人" align="center" prop="customerName" />
      <el-table-column width="120" label="发起人电话" align="center" prop="customerPhone" />
      <el-table-column width="150" label="用户地址" align="center" prop="customerAddress" />
<!--      <el-table-column label="负责人" align="center" prop="customerPhone" />-->
<!--      <el-table-column label="费用(元)" align="center" prop="quotationPrice" />-->
      <el-table-column width="150" sortable label="创建时间" align="center" prop="createTime" />
      <el-table-column width="100" label="接单人" align="center" prop="receiver" />
      <el-table-column width="200" label="维修人员" align="center" prop="proposer" />
      <el-table-column label="分配类型" align="center" prop="customerAuto">
        <template #default="scope">
          <dict-tag :options="dict.type.sys_fp" :value="scope.row.customerAuto" />
        </template>
      </el-table-column>

      <el-table-column
          fixed="right"
          label="操作"
          align="center"
          width="180"
      >
        <template slot-scope="scope">
          <router-link :to="'/gongdan/data/index/' + scope.row.customerKey" class="link-type">
            <span style="margin-right: 10px;color: #1890ff">详情</span>
          </router-link>
          <el-button
            v-if="(scope.row.customerFlag == 0 || scope.row.customerFlag == 99)"
            type="text"
            icon="Delete"
            @click="handleDisplay(scope.row)"
            v-hasPermi="['web:CustomerRepair:remove']"
          >调派
          </el-button>
          <el-button
            v-if="(scope.row.customerFlag != 7 && scope.row.customerFlag != 77)"
            type="text"
            icon="Delete"
            @click="handleClose(scope.row)"
            v-hasPermi="['web:CustomerRepair:remove']"
          >关闭
          </el-button>
          <el-button
              type="text"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['web:CustomerRepair:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

   <!--    添加工单-->
    <add-order ref="order"></add-order>

   <!--    工单调派-->
    <el-dialog v-if="dialogVisible" :visible.sync="dialogVisible" title="调派信息" width="500px" append-to-body>
      <el-form
        ref="displayRef"
        :model="dispatchForm"
        :rules="dispatchRules"
        label-width="100px"
      >
        <el-form-item label="服务单位" prop="companyId">
          <treeselect v-model="dispatchForm.companyId"   @select="changeUnit" :options="frims" :normalizer="normalizer" placeholder="选择服务单位" />
<!--          <el-cascader-->
<!--            ref="unit"-->
<!--            style="width:100%"-->
<!--            v-model="dispatchForm.companyId"-->
<!--            placeholder="请选择单位"-->
<!--            :options="frims"-->
<!--            :props="{ checkStrictly: true }"-->
<!--            @change="changeUnit"-->
<!--            clearable></el-cascader>-->
        </el-form-item>
        <el-form-item v-if="form.customerAuto == 1" label="服务人员" prop="customerPlayer">
          <el-select multiple style="width:100%" v-model="dispatchForm.customerPlayer" placeholder="请选择服务人员" :loading="bLoad">
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="`${item.nickName}【${item.userName}】`"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调派说明" prop="dispatchExplain">
          <el-input
            v-model="dispatchForm.dispatchExplain"
            type="textarea"
            placeholder="请输入调派说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="btnLoading" type="primary" @click="onSubmitInfo"
          >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!--    工单调派-->
    <el-dialog v-if="showClose" :visible.sync="showClose" title="关闭工单" width="500px" append-to-body>
      <el-form
        ref="close"
        label-width="100px"
      >
        <el-form-item label="关闭原因" prop="CloseNote"
           :rules="[
            { required: true, message: '请输入关闭原因', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model="CloseNote"
            type="textarea"
            placeholder="请输入关闭原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="close"
          >确 定</el-button
          >
          <el-button @click="showClose = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/javascript" name="CustomerRepair">
import moment from 'moment'
import {
  listCustomerRepair,
  delCustomerRepair, FrimUser, designate, closeOrder
} from '@/api/web/CustomerRepair'
import { getUser, getUserProfile } from '@/api/system/user'
import { listDept } from '@/api/system/dept'
import { handleTree } from '@/utils/ruoyi'
import addOrder from '@/views/web/CustomerRepair/addOrder'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getInfo } from '@/api/login'

export default {
  name: "Dispatch",
  components: {addOrder, Treeselect},
  dicts: ['sys_flag','sys_fp'],
  data() {
    return {
      showClose: false,
      CloseNote: '',
      searchAddress:'',
      infoWindowShow:false,
      longitude:'',
      latitude:'',
      center: {lng: 116.413384, lat: 39.910925}, // 定位位置116.413384, 39.910925
      zoom: 13, // 地图放大等级
      deptOptions: [],
      activeName: 'first',
      order: {},
      dialogVisible: false,
      btnLoading: false,
      bLoad: false,
      frims: [],
      users: [],
      sys_fp: [],
      sys_flag: [],
      CustomerRepairList: [],
      open: false,
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: '',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'desc',
        customerId: undefined,
        customerName: undefined,
        customerPhone: undefined,
        customerAddress: undefined,
        workOrderStatus: undefined,
        customerHelp: undefined,
        customerTimer: undefined,
        customerMessage: undefined,
        customerFiles: undefined,
        customerAuto: undefined,
        assignmentType: undefined,
        customerUnit: undefined,
        customerPlayer: undefined,
        customerFlag: undefined,
      },
      dispatchForm: {},
      dispatchRules: {
        customerPlayer: [
          { required: true, message: "服务人员不能为空", trigger: "blur" },
        ],
        companyId: [
          { required: true, message: "服务单位不能为空", trigger: "change" },
        ],
        customerKey: [{ required: true, message: "主键不能为空", trigger: "blur" }],
      },

      serviceType: [{

      }],
      customDept: [],
      form: {
        customerAuto: '1'
      },
    }
  },
  created() {
    this.getList();
    this.getInfo();
  },
  watch: {
    dialogVisible(newValue) {
      if (newValue) {
        listDept({ typeId: 3 }).then(response => {
          this.frims = handleTree(response.data.filter(r => r.parentId != 0).filter(r => r.deptName != '超级管理员').filter(r => r.deptName != '信息不全员工').filter(r => r.deptName != '待定位员工').filter(r => r.deptName != '平台客户'), "deptId");
          // this.frims = handleTree(response.data, "deptId");
        });
        //getAllDepts-js路径
        // getAllDepts({ typeId: 3, parentId: 100 }).then(res => {
        //   console.log(res, 'hhjhj')
        //   const arr = []
        //   res.data.forEach((item, index) => {
        //     res.data[index].label = item.deptName
        //     res.data[index].value = item.deptId
        //     arr.push(item)
        //   })
        //
        //   this.frims = arr
        // })
      }
    },
    selectFrim(newValue) {
      if (newValue !== '' && newValue !== undefined && newValue != null) {
        this.bLoad = true
        FrimUser(this.selectFrim).then(res => {
          this.users = res.rows
          this.bLoad = false
        })
      }
    }
  },
  methods: {

    handleAdd() {
      this.$refs.order.handleAdd()
    },


    /** 查询客户报修抢修列表 */
    getList(query) {
      // console.log(this.queryParams)
      // console.log(query)
      this.loading = true;
      listCustomerRepair(this.queryParams).then((response) => {
        console.log(response, '111')
        this.CustomerRepairList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryRef");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.customerKey);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    getName(value) {
      console.log(value)
      if (value) {
        getUser(value).then(response => {
          let user = response.data.user;
          console.log(user)
          this.form.customerName = user.nickName
          this.form.customerPhone = user.phonenumber
        });
      }
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row, '数据项')
      let that = this
      const customerKeys = row.customerKey || this.ids;
      this.$modal
        .confirm(`是否确认删除编号为：${customerKeys}的【${row.customerHelp}】？`)
        .then(function () {
          that.loading = true;
          return delCustomerRepair(customerKeys);
        })
        .then(() => {
          that.loading = true;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          that.loading = false;
        });
    },
    getInfo() {
      getInfo().then(res => {
        console.log(res)
        this.userId = res.data.user.userId
        // const user = res.data.user
      }).catch(error => {
      })
    },
    // 关闭工单
    handleClose(row) {
      this.showClose = true
      this.order = row
    },
    close() {
      if (this.CloseNote) {
        let params = {
          loginmanId: this.userId,   //当前登录人id
          customerKey: this.order.customerKey, //订单号
          styleOrMannerOfWriting: '',
          CloseNote: this.CloseNote
        }
        closeOrder(params).then(res=> {
          console.log(res)
          this.showClose = false
          if (res.resultCode == 200) {
            this.getList()
          } else {
            this.$modal.msgError(res.resultMsg)
          }
        })
      } else {
        this.$modal.msgError('请先输入关闭原因')
      }
    },
    handleDisplay(row) {
      this.dialogVisible = true
      this.order = row
    },
    // 调派单位选择变化
    changeUnit(value) {
      console.log(value)
      this.dispatchForm.customerPlayer = null
      // console.log(typeof value, value.length, value[value.length -1], '值变化') // this.$refs['unit'].getCheckedNodes(),
      if (value && value.length !== 0) {
        let deptId = value.deptId
        FrimUser(deptId).then(res => {
          this.users = res.rows
          console.log(res, 'tttt')
        })
      }
    },
    // 调派提交
    onSubmitInfo() {
      this.$refs["displayRef"].validate((valid) => {
        console.log(this.dispatchForm, this.$route.params, '提交的数据')
        if (valid) {
          this.btnLoading = true;
          getUserProfile().then(response => {
            // this.user = response.data.user;
            // console.log(res, '223')
            let params = {
              loginmanId: response.data.user.userId,
              customerKey: this.order.customerKey,
              orderStatus: 1,
              customerPlayer: this.dispatchForm.customerPlayer.join(','),
              companyId: this.dispatchForm.companyId[this.dispatchForm.companyId.length - 1]
            }
            console.log(params)
            designate(params)
              .then((response) => {
                if (response.resultCode == 200 || response.code == 200) {
                  this.$modal.msgSuccess("调派成功");
                  this.dialogVisible = false
                } else {
                  this.$modal.msgError(`提交调派失败${response.resultCode || response.code}:${response.resultMsg || response.msg}`);
                }
                // getList();
              })
              .finally(() => {
                this.btnLoading = false;
              });
          });
        }
      });
    },
    // 工单是否超时
    getTimeOut(item) {
      // console.log(time)
      let info = '超时';
      if (item.customerFlag == 0 || item.customerFlag == 99) {
        const t1 = new Date()
        const t2 = new Date(moment(moment(item.createTime).add(15, 'minutes')))
        const times=t2.getTime()-t1.getTime();//时间差的毫秒数
        if (times > 0) {
          var days=parseInt(times/(24*1000*3600));//计算相差的天数
          var leave=times%(24*3600*1000);//计算天数后剩余的毫秒数

          var h=parseInt(leave/(3600*1000));//计算小时数

          //计算分钟数
          var h_leave=leave%(3600*1000);
          var min=parseInt(h_leave/(60*1000));

          //计算秒数
          var min_leave=h_leave%(60*1000);
          var sec=parseInt(min_leave/1000);
          if (days >0) {
            info = days + '天' + h + '小时' + min + '分' + sec + '秒'
          } else if (days == 0 && h > 0) {
            info = h + '小时' + min + '分' + sec + '秒'
          } else {
            info = min + '分' + sec + '秒'
          }
        } else {
          info = '超时'
        }
      } else {
        if (item.receiveTime) {
          const diff = moment(moment(item.receiveTime)).diff(moment(item.createTime))
          var days=parseInt(diff/(24*1000*3600));//计算相差的天数
          var leave=diff%(24*3600*1000);//计算天数后剩余的毫秒数

          var h=parseInt(leave/(3600*1000));//计算小时数

          //计算分钟数
          var h_leave=leave%(3600*1000);
          var min=parseInt(h_leave/(60*1000));

          //计算秒数
          var min_leave=h_leave%(60*1000);
          var sec=parseInt(min_leave/1000);
          if (days >0) {
            info = days + '天' + h + '小时' + min + '分' + sec + '秒'
          } else if (days == 0 && h > 0) {
            info = h + '小时' + min + '分' + sec + '秒'
          } else {
            info = min + '分' + sec + '秒'
          }
        } else {
          info = '未接单'
        }

      }
      return info
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "web/CustomerRepair/export",
        {
          ...this.queryParams,
        },
        `CustomerRepair_${new Date().getTime()}.xlsx`
      );
    },
    // 处理部门数据
    treeData (source, id = 'deptId', parentId= 'parentId', children= 'children', rootId) {
      const newRootId = rootId || (source && source.length > 0 && source[0].parentId) || '100'
      console.log(newRootId, 'r4554545')
      if (source.length !== 0) {
        return source.filter((father) => {
          father.label = father.deptName
          father.value = father.deptId
          const parent = father
          // console.log(parent, parent[id], '数据库')
          // const branchArr = source.filter(child => parent[id] === child[parentId])// 返回每一项的子级数组
          const branchArr = source.filter(child => father.deptId == child.parentId)// 返回每一项的子级数组
          // console.log(branchArr, '哈哈哈')
          if (branchArr.length > 0) {

            parent[children] = branchArr
            // parent.children = branchArr
          } else {
            delete parent[children]
            // delete parent.children// 如果存在子级，则给父级添加一个children属性，并赋值
          }
          // return parent[parentId] === newRootId // 返回第一层
          return parent.parentId == newRootId // 返回第一层
        })
      }
    }

  }
}
</script>
<style scoped>
/deep/.el-date-editor--datetimerange.el-input__inner {
  width: 320px;
}
/deep/.el-date-editor--timerange.el-input__inner {
  width: 295px;
}
</style>
